<template>
    <n-spin :show="loading">
        <div class="main-login-box">
            <div class="login-from-box">
                <img src="../../assets/vue.svg" alt="LOGO" width="150px">
                <div class="input-form">
                    <n-form :model="form" class="form-box" :rules="rules" :ref="formInstRef">
                        <n-input type="text" placeholder="Username" v-model:value="form.username">
                            <template #icon>123</template>
                        </n-input>
                        <n-input type="password" show-password-on="click" @keydown.prevent.enter="loginBtn"
                            placeholder="Password" v-model:value="form.password" />
                        <n-button @click="loginBtn" type="success">登录</n-button>
                        <p class="register-link"><a href="#">没有账号?点我去注册</a></p>
                    </n-form>
                </div>
            </div>
        </div>
    </n-spin>
</template>
<script lang="ts" setup>
window.message = useMessage()
import { FormInst, useMessage } from 'naive-ui';
import { ref } from 'vue';
import { login } from '../../api/user';
import { setToken } from '../../util/token';
import { userStore } from '../../store/userStore';
const form = ref({
    username: '',
    password: '',
});

const loading = ref(false)

const formInstRef = ref<FormInst | null>(null)

const userInfo = userStore()


const rules = ref({
    form: {
        username: {
            required: true,
            trigger: 'blur'
        }
    }
})

const loginBtn = () => {
    if (loading.value) return;
    loading.value = !loading.value
    const loginIng = window.message.loading('LOGIN')

    setTimeout(() => {
        login(form.value.username, form.value.password).then((e) => {
            if (e.data) {
                userInfo.setToken(e.data)
                window.message.loading("登录成功..稍等")
                setTimeout(() => {
                    window.location.href = "/"
                }, 1000);
            }
        }).finally(() => {
            loading.value = !loading.value
            loginIng.destroy()
        })
    }, 1000);
}
</script>

<style lang="scss" scoped>
.main-login-box {
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background-image: linear-gradient(to bottom, #e6eff4, #fcecf6);

    .login-from-box {
        width: 300px;
        height: 450px;
        background: #ffffff;
        border-radius: 5px;
        box-shadow: 0 0 6px 1px #1f1f1f2d;


        display: flex;
        justify-content: center;
        align-items: center;
        flex-wrap: wrap;

        .form-box {
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
            gap: 15px;
            padding: 10px;
        }
    }
}
</style>